package com.ws.universal.tools.livedatabus;


import androidx.lifecycle.MutableLiveData;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:ws 中间人 代理
 * @date: 2019/10/24 8:50
 * @desc
 */
public class LiveDataBus {


    //双重锁模式
    //线程安全，延迟初始化。这种方式采用双锁机制，安全且在多线程情况下能保持高性能。
    private static LiveDataBus liveDataBus;
    //创建一个容器 用来装载所以订阅者
    private Map<String, MutableLiveData> bus;

    public LiveDataBus() {
        bus = new HashMap<>();
    }

    public static LiveDataBus getInstace() {
        if (liveDataBus == null) {
            synchronized (LiveDataBus.class) {
                if (liveDataBus == null) {
                    liveDataBus = new LiveDataBus();
                }
            }


        }
        return liveDataBus;
    }

    //注册订阅者
    public synchronized <T> MutableLiveData<T> with(String key, Class<T> type) {
        if (!bus.containsKey(key)) {
            bus.put(key, new MutableLiveData<Object>());
        }
        return (MutableLiveData<T>) bus.get(key);
    }


}
